package com.bianpai.execution;

import com.bianpai.core.Flow;
import com.bianpai.core.FlowContext;
import com.bianpai.core.Node;
import com.bianpai.core.NodeResult;
import com.bianpai.log.FlowLogger;

/**
 * 顺序执行策略，按照节点添加的顺序依次执行
 */
public class SequentialExecutionStrategy implements ExecutionStrategy {
    
    @Override
    public boolean execute(Flow flow, FlowContext context, FlowLogger logger) {
        for (Node node : flow.getNodes()) {
            logger.logNodeStart(node, context);
            
            try {
                NodeResult result = node.execute(context);
                context.setNodeResult(node.getId(), result);
                
                logger.logNodeComplete(node, context, result);
                
                if (!result.isSuccess()) {
                    return false; // 节点执行失败，终止流程
                }
            } catch (Exception e) {
                NodeResult result = NodeResult.failure("Node execution error: " + e.getMessage(), e);
                context.setNodeResult(node.getId(), result);
                logger.logNodeError(node, context, e);
                return false; // 节点执行异常，终止流程
            }
        }
        
        return true; // 所有节点执行成功
    }
}